<template>
  <div :class="prefixCls">
    <Spin :spinning="loading" size="large" :wrapperClassName="[getShowMultipleTab ? 'iframe-view-content-tab-bar-height' : 'iframe-view-content']">
      <iframe
        :src="iframeSrc"
        :class="`${prefixCls}__main`"
        ref="frameRef"
        @load="hideLoading"
      ></iframe>
    </Spin>
  </div>
</template>
<script lang="ts" setup>
  import { ref, unref, onMounted, onUnmounted } from 'vue';
  import { Spin } from 'ant-design-vue';
  import { propTypes } from '@gui-pkg/utils';
  import { useMultipleTabSetting } from '@/hooks/setting/useAppSetting';

  const emit = defineEmits(['message']);
  defineProps({
    iframeSrc: propTypes.string.def(''),
  });

  const prefixCls = 'iframe-page';
  const loading = ref(true);
  const frameRef = ref<HTMLFrameElement>();
  const { getShowMultipleTab } = useMultipleTabSetting();

  function hideLoading() {
    loading.value = false;
    calcHeight();
  }

  const messageHandler = (e: MessageEvent) => {
    emit('message', e.data);
  };

  const postMessage = (message: any, tragetOrigin: string, transfer?: Transferable[]) => {
    const iframe = unref(frameRef);
    if (!iframe) return;
    iframe.contentWindow?.postMessage(message, tragetOrigin, transfer);
  };

  const reload = () => {
    loading.value = true;
    const iframe = frameRef.value;
    if (!iframe) return;
    iframe.contentWindow?.location.reload();
    loading.value = false;
  };

  onMounted(() => {
    window.addEventListener('message', messageHandler);
  });

  onUnmounted(() => {
    window.removeEventListener('message', messageHandler);
  });

  defineExpose({ postMessage, reload });
</script>
<style lang="less" scoped>
  .iframe-page {
    width: 100%;
    height: 100%;
    .ant-spin-nested-loading {
      position: relative;
      height: 100%;
    }
    ::v-deep(.ant-spin-container) {
      width: 100%;
      height: 100%;
    };

    .iframe-view-content {
      position: relative;
      height: calc(100vh - var(--header-height));
      overflow: auto;
    }

    .iframe-view-content-tab-bar-height {
      position: relative;
      height: calc(100vh - var(--header-height) - var(--tab-bar-height));
      overflow: auto;
    }

    &__mask {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
    }

    &__main {
      display: block;
      box-sizing: border-box;
      width: 100%;
      height: 100%;
      overflow: hidden;
      border: 0;
      background-color: #fff;
    }
  }
</style>
